package com.cl.blog.web.client;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cl.blog.annotation.Login;
import com.cl.blog.common.Result;
import com.cl.blog.entity.BContent;
import com.cl.blog.entity.BTag;
import com.cl.blog.entity.BType;
import com.cl.blog.entity.BUser;
import com.cl.blog.exception.WebException;
import com.cl.blog.service.BContentService;
import com.cl.blog.service.BTagService;
import com.cl.blog.service.BTypeService;
import com.cl.blog.service.BUserService;
import com.cl.blog.vo.ClientAddContent;
import com.cl.blog.web.PageController;
import lombok.extern.java.Log;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 付
 * @Date 2024-03-15 15:20
 * @Version 1.0
 * @description
 * @since 1.0
 */
@RestController
@RequestMapping("/user/blog")
public class BlogController extends PageController {
	@Resource
	BContentService bContentService;
	@Resource
	BTypeService bTypeService;
	@Resource
	BTagService bTagService;
	@Resource
	BUserService bUserService;

	/**
	 * 当有id时，就根据id，否则默认
	 *
	 * @param id
	 * @return
	 */
	@GetMapping("/list")
	@Login
	public Result list(Long id) {
		return Result.success(bContentService.queryList(getPage(), id));
	}

	@GetMapping("/all")
	@Login
	public Result getList(Integer size) {

		Page<BContent> page = bContentService.page(new Page<>(size, 12), new QueryWrapper<BContent>()
				.eq("status", 2)
				.eq("is_delete", 0)
		);

		for (BContent b : page.getRecords()) {
			BUser bUser = bUserService.getById(b.getUserId());
			b.setAuthor(bUser.getNickname());
			BType bType = bTypeService.getById(b.getTypeId());
			if (bType == null) {
				b.setTypeName("未知");
			} else {
				b.setTypeName(bType.getName());
			}
		}
		return Result.success(page);
	}


	@PostMapping("/insert")
	@Login
	public Result insertBlog(@Validated @RequestBody ClientAddContent content, HttpServletRequest request) {
		String token = request.getHeader("token");
		boolean b = bContentService.insertBlog(content, token);
		if (b) {
			return Result.success();
		}
		return Result.error("失败了");
	}

	/**
	 * 根据文章id 获取文章
	 *
	 * @param id 文章id
	 * @return 文章具体信息
	 */
	@GetMapping("/one")
	public Result getOne(Integer id) {
		BContent bContent = bContentService.getById(id);
		if (bContent == null) {
			throw new WebException("抱歉，文章不存在");
		}
		BUser bUser = bUserService.getById(bContent.getUserId());
		BType bType = bTypeService.getById(bContent.getTypeId());
		bContent.setAuthor(bUser.getNickname());
		bContent.setTypeName(bType.getName());

		return Result.success(bContent);
	}

}
